package edu.scau.mis.web.controller.pos;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.scau.mis.core.domain.AjaxResult;
import edu.scau.mis.pos.domain.Product;
import edu.scau.mis.pos.domain.Promotion;
import edu.scau.mis.pos.service.IPromotionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/promotion")
public class PromotionController {
    @Autowired
    private IPromotionService promotionService;


    @GetMapping("/listAll")
    public AjaxResult listAll() {
        List<Promotion> promotions = promotionService.selectList();
        return AjaxResult.success(promotions);
    }
    @GetMapping("/page")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, Promotion promotion) {
        PageHelper.startPage(pageNum,pageSize);
        List<Promotion> list = promotionService.selectByPage(promotion);
        PageInfo<List> pageInfo = new PageInfo(list);
        return AjaxResult.success(pageInfo);
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody Promotion promotion) {
        int result = promotionService.addPromotion(promotion);
        return result > 0 ? AjaxResult.success() : AjaxResult.error("添加失败");
    }

    @PostMapping("/update")
    public AjaxResult update(@RequestBody Promotion promotion) {
        int result = promotionService.updatePromotion(promotion);
        return result > 0 ? AjaxResult.success() : AjaxResult.error("更新失败");
    }

    @DeleteMapping("/deleteById/{promotionId}")
    public AjaxResult delete(@PathVariable String promotionId) {
        int result = promotionService.deletePromotion(promotionId);
        return result > 0 ? AjaxResult.success() : AjaxResult.error("删除失败");
    }

//    private Promotion convertFormToEntity(PromotionForm form) {
//        Promotion promotion = new Promotion();
//        promotion.setPromotionId(form.getId() != null ? Integer.parseInt(form.getId().replace(ID_PREFIX, "")) : null);
//        promotion.setPromotionName(form.getName());
//        promotion.setPromotionType(getPromotionTypeString(form.getPromotionType()));
//        promotion.setStatus(form.getStatus());
//        promotion.setContent(form.getContent());
//        promotion.setStartDate(parseDateTime(form.getStartTime()));
//        promotion.setEndDate(parseDateTime(form.getEndTime()));
//
//        if (form.getPromotionType() == PromotionType.Discount) {
//            promotion.setDiscount(BigDecimal.valueOf(form.getDiscount()));
//        } else if (form.getPromotionType() == PromotionType.FullReduce) {
//            promotion.setMinAmount(form.getMinAmount());
//            promotion.setReduceAmount(form.getReduceAmount());
//        }
//
//        return promotion;
//    }

//    private String getPromotionTypeString(PromotionType type) {
//        switch (type) {
//            case Discount: return "Discount";
//            case FullReduce: return "FullReduce";
//            case Original: return "Original";
//            default: return "Original";
//        }
//    }
//
//    private Date parseDateTime(String dateTimeStr) {
//        try {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//            return sdf.parse(dateTimeStr);
//        } catch (ParseException e) {
//            throw new RuntimeException("日期格式错误");
//        }
//    }


    @GetMapping("/listByTypeAndStatus")
    public List<Promotion> getPromotionsByTypeAndStatus(@RequestParam String type) {
        return promotionService.getPromotionsByTypeAndStatus(type);
    }


    @PostMapping("/apply")
    public AjaxResult applyPromotion(@RequestParam String promotionId, @RequestParam double totalAmount) {
        // 1️⃣ 从数据库查询对应的促销信息
        Promotion promotion = promotionService.selectPromotionById(promotionId);

        if (promotion == null) {
            return AjaxResult.error("促销规则不存在");
        }

        double finalAmount = totalAmount; // 默认是原价

        // 2️⃣ 判断促销类型并执行对应计算
        String content = promotion.getContent(); // 获取促销规则内容
        if (content.startsWith("满") && content.contains("减")) {
            // 满减活动，例如：满500减50
            String[] parts = content.split("满|减");
            double minAmount = Double.parseDouble(parts[1]);
            double reduceAmount = Double.parseDouble(parts[2]);
            if (totalAmount >= minAmount) {
                finalAmount = totalAmount - reduceAmount;
            }
        } else if (content.startsWith("折扣")) {
            // 折扣活动，例如：折扣8折
            double discountRate = Double.parseDouble(content.replaceAll("[^\\d.]", "")) / 10.0;
            finalAmount = totalAmount * discountRate;
        }

        // 如果是 "原价购买"，则 finalAmount 保持原价
        return AjaxResult.success(finalAmount);
    }





}
